package handler

import (
	"context"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"ihome/models"
	"ihome/utils"
	"strconv"

	"github.com/micro/go-micro/util/log"

	getHouses "ihome/proto/getHouses"
)

type GetHouses struct{}

func (e *GetHouses) SrvGetHouses(ctx context.Context, req *getHouses.Request, rsp *getHouses.Response) error {
	logs.Info("搜索房屋 GetHouses /api/v1.0/houses")

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	aid, _ := strconv.Atoi(req.Aid)
	//sd := req.Sd
	//ed := req.Ed
	//sk := req.Sk
	//page, _ := strconv.Atoi(req.P)

	o := orm.NewOrm()
	qs := o.QueryTable("house")
	var houses []models.House

	num, err := qs.Filter("area_id", aid).All(&houses)

	if err != nil {
		logs.Info("搜索房屋错误")
		rsp.Code = utils.RecodeParamerr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	totalPage := int(num)/models.HOUSE_LIST_PAGE_CAPACITY + 1
	housePage := 1

	var houseList []interface{}
	for _, house := range houses {
		o.LoadRelated(&house, "Area")
		o.LoadRelated(&house, "User")
		o.LoadRelated(&house, "Images")
		o.LoadRelated(&house, "Facilities")
		houseList = append(houseList, house.To_house_info())
	}

	rsp.TotalPage = int64(totalPage)
	rsp.CurrentPage = int64(housePage)
	rsp.Houses, _ = json.Marshal(houseList)

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *GetHouses) Stream(ctx context.Context, req *getHouses.StreamingRequest, stream getHouses.GetHouses_StreamStream) error {
	log.Logf("Received GetHouses.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&getHouses.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *GetHouses) PingPong(ctx context.Context, stream getHouses.GetHouses_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&getHouses.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
